package com.www.applyword.ui.home;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.classic.adapter.CommonRecyclerAdapter;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.style.citypickerview.CityPickerView;
import com.www.applyword.Constants.Constants;
import com.www.applyword.R;
import com.www.applyword.adapter.GirdDropDownAdpter5;
import com.www.applyword.adapter.JobPositionTimeAdapter;
import com.www.applyword.adapter.JobPositionTimeAdapter2;
import com.www.applyword.base.BaseActivity;
import com.www.applyword.bean.LoginBean;
import com.www.applyword.bean.OrderDetail;
import com.www.applyword.event.EventConstants;
import com.www.applyword.event.MessageEvent;
import com.www.applyword.http.CallBack;
import com.www.applyword.http.HttpClient;
import com.www.applyword.main.LocationActiviy2;
import com.www.applyword.ui.my.JobPostionActivity;
import com.www.applyword.ui.my.ResetPayActivity;
import com.www.applyword.utils.CommonUtil;
import com.www.applyword.utils.SPUtil;
import com.www.applyword.utils.Utils;

import org.greenrobot.eventbus.EventBus;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.www.applyword.utils.Utils.getDeviceDensity;

/**
 * author : huang
 * date   : 2019/10/21 0021 18:10
 * version: 1.0
 *
 * @author Administrator
 */
public class PostJobActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.cb_knot)
    CheckBox cbKnot;
    @BindView(R.id.cb_daily)
    CheckBox cbDaily;
    @BindView(R.id.cb_month)
    CheckBox cbMonth;
    @BindView(R.id.tv_welfare)
    TextView tvWelfare;
    @BindView(R.id.tv_record)
    TextView tvRecord;
    @BindView(R.id.tv_year_time)
    TextView tvYearTime;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.tv_year)
    TextView tvYear;
    @BindView(R.id.tv_word_time)
    TextView tvWordTime;
    @BindView(R.id.tv_word_end_time)
    TextView tv_word_end_time;
    @BindView(R.id.tv_word_address)
    TextView tvWordAddress;
    @BindView(R.id.cb1)
    CheckBox cb1;
    @BindView(R.id.cb2)
    CheckBox cb2;
    @BindView(R.id.cb3)
    CheckBox cb3;
    @BindView(R.id.cb4)
    CheckBox cb4;
    @BindView(R.id.et_order_title)
    EditText etOrderTitle;
    @BindView(R.id.tv_order_positionName)
    TextView tvOrderPositionName;
    @BindView(R.id.tv_agreement)
    TextView tv_agreement;
    @BindView(R.id.tv_order_positionType)
    TextView tvOrderPositionType;
    @BindView(R.id.et_order_number)
    EditText etOrderNumber;
    @BindView(R.id.et_Order_Salary)
    EditText etOrderSalary;
    @BindView(R.id.et_Order_WorkTerm)
    EditText etOrderWorkTerm;
    @BindView(R.id.et_Order_WorkAddress)
    TextView etOrderWorkAddress;
    @BindView(R.id.et_Order_PositionDescribe)
    EditText etOrderPositionDescribe;
    @BindView(R.id.et_Order_Contacts)
    EditText etOrderContacts;
    @BindView(R.id.tv_word_time2)
    TextView tv_word_time2;
    @BindView(R.id.et_Order_ContactsPhone)
    EditText etOrderContactsPhone;
    @BindView(R.id.et_Order_Mail)
    EditText etOrderMail;
    //自行添加一些string
    private List<String> gradeData = new ArrayList<>();
    private PopupWindow mValidatePayPasswordPopWindow;

    private OptionsPickerView pvOptions;
    private String typeName;
    private int order_salaryType;
    private int order_type;
    private String position_id;
    private String address;


    private Map<String,Boolean> gvChooseMap=new HashMap<String, Boolean>();
    private OrderDetail orderDetail;

    private JobPositionTimeAdapter mHotJobAdapter;
    private JobPositionTimeAdapter2 mHotJobAdapter2;
    private String time;
    private String time2;

    private String date[] = {"9:00", "9:30","10:00","10:30","11:00","11:30","12:00","12:30","13:00","13:30","14:00","14:30"
            ,"15:00", "15:30","16:00","16:30","17:00","17:30","18:00","18:30","19:00","19:30","20:00","20:30"
            ,"21:00", "21:30","22:00","22:30","23:00","23:30","24:00","00:30","01:00","01:30","02:00","02:30"
            ,"03:00", "03:30","04:00","04:30","05:00","05:30","06:00","06:30","07:00","07:30","08:00","08:30"};

    private String date2[] = {"100", "200","300","400","500","600","700","800","900","1000","1500","2000"
            ,"2500", "3000","3500","4000","4500","5000","5500","6000","6500","7000","7500","8000"
            ,"8500", "9000","9500","10000"};
    private double order_bond;
    private String order_id;
    private Double latitude;
    private Double longitude;
    private boolean flag;
    private int type2;
    private String new_Order_id;
    private Double order_bond1;


    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.post_job_activity);
        setTitle("发布招聘");
        initData();
    }

    private void initData() {
        cb1.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
        cb2.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
        cb4.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
        cb3.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
        cbKnot.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
        cbDaily.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
        cbMonth.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
        tv_agreement.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
    }

    @Override
    protected void loadData() {
        orderDetail = (OrderDetail) getIntent().getSerializableExtra("OrderDetail");
        if (null != orderDetail){
            latitude =   orderDetail.getOrder().getOrder_WorkLat();
            longitude =   orderDetail.getOrder().getOrder_WorkLng();
            if (!TextUtils.isEmpty(orderDetail.getOrder().getOrder_Welfare())) {
                tvWelfare.setText(orderDetail.getOrder().getOrder_Welfare());
            }

          //  .setText(orderDetail.getOrder().getOrder_Title());  //et_order_number
            if (orderDetail.getOrder().getOrder_PositionType() == 1){
                tvOrderPositionType.setText("全职");
            }else {
                tvOrderPositionType.setText("兼职");
            }
            //工作年限
            tvYearTime.setText(orderDetail.getOrder().getOrder_WorkYears());
            tv_word_time2.setText(orderDetail.getOrder().getOrder_HourStartTime() + "—" + orderDetail.getOrder().getOrder_HourEndTime());
            etOrderSalary.setText(orderDetail.getOrder().getOrder_Salary());
            tvOrderPositionName.setText(orderDetail.getOrder().getOrder_PositionName());
           etOrderNumber.setText(orderDetail.getOrder().getOrder_Number() + "");
            if (orderDetail.getOrder().getOrder_SalaryType() == 0) {
                cbKnot.setChecked(true);
               // tvOrderSalary.setText(orderDetail.getOrder().getOrder_Salary() + "/时");
              //  tvArea.setText("时结 | " + orderDetail.getOrder().getOrder_WorkAddress());
            } else if (orderDetail.getOrder().getOrder_SalaryType() == 1) {
                cbDaily.setChecked(true);
              //  tvOrderSalary.setText(orderDetail.getOrder().getOrder_Salary() + "/日");
              //  tvArea.setText("日结 | " + orderDetail.getOrder().getOrder_WorkAddress());
            } else {
                cbMonth.setChecked(true);
              //  tvOrderSalary.setText(orderDetail.getOrder().getOrder_Salary() + "/月");
               // tvArea.setText("月结 | " + orderDetail.getOrder().getOrder_WorkAddress());
            }
            if (orderDetail.getOrder().getOrder_Type() == 0) {   ////0只可承包；1承包和个人；2只可个人；Order_Type
                cb1.setChecked(true);
                order_type = 0;
               // tvOrderSalary.setText(orderDetail.getOrder().getOrder_Salary() + "/时");
              //  tvArea.setText("时结 | " + orderDetail.getOrder().getOrder_WorkAddress());
            } else if (orderDetail.getOrder().getOrder_Type() == 1) {
                cb2.setChecked(true);
                order_type = 1;
              //  tvOrderSalary.setText(orderDetail.getOrder().getOrder_Salary() + "/日");
              //  tvArea.setText("日结 | " + orderDetail.getOrder().getOrder_WorkAddress());
            } else {
                cb3.setChecked(true);
                order_type = 2;
              //  tvOrderSalary.setText(orderDetail.getOrder().getOrder_Salary() + "/月");
               // tvArea.setText("月结 | " + orderDetail.getOrder().getOrder_WorkAddress());
            }
            tvSex.setText(orderDetail.getOrder().getOrder_Sex());
            tvYear.setText(orderDetail.getOrder().getOrder_Age());
            tvWordTime.setText(orderDetail.getOrder().getOrder_WorkYears());
            //教育经历
            tvRecord.setText(orderDetail.getOrder().getOrder_Education());
            etOrderPositionDescribe.setText(orderDetail.getOrder().getOrder_PositionDescribe());

           // params.put("Order_EndTime",tv_word_end_time.getText().toString().split(" ")[0]);
         //   params.put("Order_StartTime",tvWordTime.getText().toString().split(" ")[0]);
            tvWordTime.setText(orderDetail.getOrder().getOrder_StartTime().split(" ")[0]);
            tv_word_end_time.setText(orderDetail.getOrder().getOrder_EndTime().split(" ")[0]);
            tvWordAddress.setText(orderDetail.getOrder().getOrder_WorkAddress());
            etOrderWorkAddress.setText(orderDetail.getOrder().getOrder_WorkDetailedAddress());
          //  userInfo_nickName = orderDetail.getUser().getUserInfo_NickName();
         //   userInfo_mobile = orderDetail.getUser().getUserInfo_Mobile();
            etOrderContactsPhone.setText(orderDetail.getOrder().getOrder_ContactsPhone());
            //公司信息
            if (null != orderDetail.getCertificationBean() && !TextUtils.isEmpty(orderDetail.getCertificationBean().getEnterpriseCertification_Name())) {
              //  type2 = 0;
             //   ImageUtil.setImage(stCompany.getLeftIconIV(), orderDetail.getCertificationBean().getEnterpriseCertification_Logo());
              //  stCompany.getLeftTopTextView().setText(orderDetail.getCertificationBean().getEnterpriseCertification_Name());
                //联系人
                etOrderContacts.setText(orderDetail.getCertificationBean().getEnterpriseCertification_UserName());
              //  etOrderContactsPhone.setText(orderDetail.getCertificationBean().getEnterpriseCertification_UserName());
            } else {
               // type2 = 1;
              //  ImageUtil.setImage(stCompany.getLeftIconIV(), orderDetail.getUser().getUserInfo_HeadImg());
              //  stCompany.getLeftTopTextView().setText(orderDetail.getUser().getUserInfo_NickName());
                etOrderContacts.setText(orderDetail.getUser().getUserInfo_RealName());
              //  ll_bond.setVisibility(View.GONE);
             //   tv_com.setText("个人信息");
            }
        }
        type2 = getIntent().getIntExtra("type", 0);
        if (type2 == 1){
            if (!TextUtils.isEmpty(orderDetail.getOrder().getOrder_Welfare())) {
                tvWelfare.setEnabled(false);
            }
            tvOrderPositionType.setEnabled(false);
            tvYearTime.setEnabled(false);
            tv_word_time2.setEnabled(false);
            //价格可以编辑
         //   etOrderSalary.setClickable(false);
            tvOrderPositionName.setEnabled(false);
            etOrderNumber.setEnabled(false);
            cbKnot.setEnabled(false);
            cbDaily.setEnabled(false);
            cbMonth.setEnabled(false);
          //  cb1.setEnabled(false);
          //  cb2.setEnabled(false);
          //  cb3.setEnabled(false);

            tvSex.setEnabled(false);
            tvYear.setEnabled(false);
            tvWordTime.setEnabled(false);
            tvRecord.setEnabled(false);
            etOrderPositionDescribe.setEnabled(false);

            tvWordTime.setEnabled(false);
            tv_word_end_time.setEnabled(false);
            tvWordAddress.setEnabled(false);
            etOrderWorkAddress.setEnabled(false);
            cb4.setChecked(true);
           // etOrderContactsPhone.setClickable(false);

        }
    }


    @OnClick({R.id.cb_knot, R.id.cb_daily, R.id.cb_month, R.id.tv_welfare, R.id.tv_record, R.id.tv_year_time, R.id.tv_sex, R.id.tv_year,
            R.id.tv_word_time, R.id.tv_word_address, R.id.cb1, R.id.cb2, R.id.cb3, R.id.cb4, R.id.tv_word_end_time,
            R.id.sb_addOrder,R.id.tv_order_positionName,R.id.tv_order_positionType,R.id.tv_agreement,R.id.et_Order_WorkAddress,R.id.tv_word_time2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cb_knot:
                order_salaryType = 0;
                cbDaily.setChecked(false);
                cbMonth.setChecked(false);
                break;
            case R.id.cb_daily:
                order_salaryType = 1;
                cbKnot.setChecked(false);
                cbMonth.setChecked(false);
                break;
            case R.id.cb_month:
                order_salaryType = 2;
                cbKnot.setChecked(false);
                cbDaily.setChecked(false);
                break;
                //职位福利
            case R.id.tv_welfare:
                showWelfare();
                break;
            case R.id.tv_record:
                typeName = "学历";
                showSex(2);
                break;
            case R.id.tv_year_time:
                typeName = "工作年限";
                showSex(3);
                break;
            case R.id.tv_sex:
                typeName = "性别";
                showSex(1);
                break;
            case R.id.tv_year:
                typeName = "年龄要求";
                showSex(4);
                break;
            case R.id.tv_word_time:
                typeName = "开始工作时间";
                showWordTime(1);
                break;
            case R.id.tv_word_end_time:
                typeName = "开始结束时间";
                showWordTime(2);
                break;
            case R.id.tv_word_address:
                showAddress();
                break;
            case R.id.cb1:
                order_type = 0;
                cb2.setChecked(false);
                cb3.setChecked(false);
                break;
            case R.id.cb2:
                order_type = 1;
                cb1.setChecked(false);
                cb3.setChecked(false);
                break;
            case R.id.cb3:
                order_type = 2;
                cb1.setChecked(false);
                cb2.setChecked(false);
                break;
            case R.id.cb4:
               // order_type = 0;
                break;
            case R.id.sb_addOrder:
                if (type2 == 1){
                    turnOutOrder();
                }else{
                    addOrder();
                }

                break;
                //个人协议
            case R.id.tv_agreement:
                startActivity(new Intent(this,AgreementActivity.class).putExtra("type", 1));
              //  Utils.startActivity(AgreementActivity.class);
                break;
            case R.id.tv_order_positionName: //职位名称
                Intent intent = new Intent(PostJobActivity.this, JobPostionActivity.class);
                //   startActivity(intent);
                startActivityForResult(intent, 30);
                overridePendingTransition(R.anim.push_top_in,
                        R.anim.push_top_out);
                break;
            case R.id.tv_order_positionType: //职位类别
                typeName = "职位类别";
                showSex(5);
                break;
            //选择地址
            case R.id.et_Order_WorkAddress:
                startActivityForResult(new Intent(this, LocationActiviy2.class), 5);
                break;
            //工作时间
            case R.id.tv_word_time2:
                showStartTime();
                break;
            default:
        }
    }

    /**
     * 转发
     */
    private void turnOutOrder() {
        Map<String, Object> params = new HashMap<>();
        params.put("OrderID",orderDetail.getOrder().getOrder_ID());
        params.put("UserID",SPUtil.getString(Constants.USERID));
        params.put("Price",etOrderSalary.getText().toString().trim());
        params.put("ContactsPhone",etOrderContactsPhone.getText().toString().trim());
        params.put("Contacts",etOrderContacts.getText().toString().trim());
        params.put("Mail",etOrderMail.getText().toString().trim());
        params.put("Type", order_type + "");
        HttpClient.get(PostJobActivity.this, Constants.TURNOUTORDER, params,new CallBack<OrderDetail>() {
            @Override
            public void onSuccess(OrderDetail result) {
                order_bond = result.Order_Bond;
                new_Order_id = result.Order_ID;
                showPossWord();
            }
        });
    }


    public TextView tv_prv_select;
    public TextView tv_prv_select2;

    private void showStartTime() {
        hideInput2();
        setBackgroundAlpha((float) 0.4);
        View contentView = LayoutInflater.from(this).inflate(R.layout.popwindow_job_time, null);
        final TextView tv_cancel = contentView.findViewById(R.id.tv_cancel);
        final TextView tv_ok = contentView.findViewById(R.id.tv_ok);
        final RecyclerView rv_left = contentView.findViewById(R.id.rv_left);
        final RecyclerView rv_right = contentView.findViewById(R.id.rv_right);

        rv_left.setLayoutManager(new LinearLayoutManager(PostJobActivity.this));
        rv_left.setItemAnimator(new DefaultItemAnimator());
        mHotJobAdapter = new JobPositionTimeAdapter(PostJobActivity.this);
        rv_left.setAdapter(mHotJobAdapter);
        mHotJobAdapter.addAll(Arrays.asList(date));

        rv_right.setLayoutManager(new LinearLayoutManager(PostJobActivity.this));
        rv_right.setItemAnimator(new DefaultItemAnimator());
        mHotJobAdapter2 = new JobPositionTimeAdapter2(PostJobActivity.this);
        rv_right.setAdapter(mHotJobAdapter2);
        mHotJobAdapter2.addAll(Arrays.asList(date));

        mHotJobAdapter.setOnItemClickListener(new CommonRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.ViewHolder viewHolder, View view, int i) {
                TextView tv_check =  view.findViewById(R.id.tv_job);
                if (tv_prv_select == tv_check) {
                    tv_check.setSelected(false);
                    tv_prv_select = null;
                    return;
                }

                tv_check.setSelected(true);
                if (tv_prv_select != null) {
                    tv_prv_select.setSelected(false);
                }
                tv_prv_select = tv_check;
                time = date[i];
            }
        });

        mHotJobAdapter2.setOnItemClickListener(new CommonRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.ViewHolder viewHolder, View view, int i) {
                TextView tv_check =  view.findViewById(R.id.tv_job);
                if (tv_prv_select2 == tv_check) {
                    tv_check.setSelected(false);
                    tv_prv_select2 = null;
                    return;
                }

                tv_check.setSelected(true);
                if (tv_prv_select2 != null) {
                    tv_prv_select2.setSelected(false);
                }
                tv_prv_select2 = tv_check;
                time2 = date[i];
            }
        });

        tv_cancel.setOnClickListener(v -> mValidatePayPasswordPopWindow.dismiss());
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(time)){
                    Utils.showToastSafe("请选择开始时间");
                    return;
                }
                if (TextUtils.isEmpty(time2)){
                    Utils.showToastSafe("请选择结束时间");
                    return;
                }
                if (time.equals(time2)){
                    Utils.showToastSafe("开始时间等于结束时间");
                    return;
                }
                tv_word_time2.setText(time + "—" + time2);
                mValidatePayPasswordPopWindow.dismiss();
            }
        });

        mValidatePayPasswordPopWindow = new PopupWindow(contentView,
                (int) (getDeviceDensity().widthPixels), LinearLayout.LayoutParams.WRAP_CONTENT, true);
        mValidatePayPasswordPopWindow.setContentView(contentView);
        View rootView = LayoutInflater.from(PostJobActivity.this).inflate(R.layout.hot_job_activity, null);
        mValidatePayPasswordPopWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
        mValidatePayPasswordPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBackgroundAlpha(1);
            }
        });
    }

    private String date3[] = {"五险一金", "包住","包吃","带薪年假","年底双薪","周末双休","交通补助","加班补助","有提成","饭补","话补","房补"};
    private    Map<Integer, String> map = new HashMap<>();
    //职位福利
    private void showWelfare() {
        hideInput2();
        setBackgroundAlpha((float) 0.4);
        View contentView = LayoutInflater.from(this).inflate(R.layout.popwindow_welfare_password, null);
        final TextView tv_cancel = contentView.findViewById(R.id.tv_cancel);
        final TextView tv_ok = contentView.findViewById(R.id.tv_ok);
        final GridView gv = contentView.findViewById(R.id.gv);
        GirdDropDownAdpter5 cityAdapter = new GirdDropDownAdpter5(this, Arrays.asList(date3));
        gv.setAdapter(cityAdapter);

        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (view.isActivated()){
                    view.setActivated(false);
                    gvChooseMap.put(date3[position], false);
                }else {
                    view.setActivated(true);
                    gvChooseMap.put(date3[position], true);
                }
            }
        });

        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gvChooseMap.clear();
                mValidatePayPasswordPopWindow.dismiss();
            }
        });
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (gvChooseMap.size() > 0){
                    StringBuffer sb = new StringBuffer();
                    //遍历map
                    for(Map.Entry<String,Boolean> entry : gvChooseMap.entrySet()){
                        String strkey = entry.getKey();
                        boolean flag = entry.getValue();
                        if(flag==true){
                            sb.append(strkey+",");
                        }
                    }
                    tvWelfare.setText(sb.toString().substring(0, sb.toString().length()-1));
                    gvChooseMap.clear();
                    mValidatePayPasswordPopWindow.dismiss();
                }
            }
        });

        mValidatePayPasswordPopWindow = new PopupWindow(contentView,
                (int) (getDeviceDensity().widthPixels), LinearLayout.LayoutParams.WRAP_CONTENT, true);
        mValidatePayPasswordPopWindow.setContentView(contentView);
        View rootView = LayoutInflater.from(PostJobActivity.this).inflate(R.layout.hot_job_activity, null);
        mValidatePayPasswordPopWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
        mValidatePayPasswordPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBackgroundAlpha(1);
            }
        });
    }

    private void hideInput2() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    private void setBackgroundAlpha(float v) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = v;
        getWindow().setAttributes(lp);
    }

    private void addOrder() {
        if (TextUtils.isEmpty(etOrderTitle.getText().toString().trim())){
          //  Utils.showToastSafe(etOrderTitle.getHint().toString());
         //   return;
        }
        if (TextUtils.isEmpty(tvOrderPositionName.getText().toString().trim())){
            Utils.showToastSafe(tvOrderPositionName.getHint().toString());
            return;
        }
        if (TextUtils.isEmpty(tvOrderPositionType.getText().toString().trim())){
            Utils.showToastSafe(tvOrderPositionType.getHint().toString());
            return;
        }
        if (TextUtils.isEmpty(etOrderNumber.getText().toString().trim())){
            Utils.showToastSafe(etOrderNumber.getHint().toString());
            return;
        }
        if (TextUtils.isEmpty(etOrderSalary.getText().toString().trim())){
            Utils.showToastSafe(etOrderSalary.getHint().toString());
            return;
        }
        if (!cbKnot.isChecked() && !cbMonth.isChecked() && !cbDaily.isChecked()){
            Utils.showToastSafe("请选择结算方式");
            return;
        }
        if (TextUtils.isEmpty(tvWelfare.getText().toString().trim())){ //福利
            Utils.showToastSafe(tvWelfare.getHint().toString());
            return;
        }
        if (TextUtils.isEmpty(tvRecord.getText().toString().trim())){
            Utils.showToastSafe(tvRecord.getHint().toString());
            return;
        }
        if (TextUtils.isEmpty(tvYearTime.getText().toString().trim())){
            Utils.showToastSafe(tvYearTime.getHint().toString());
            return;
        }
        if (TextUtils.isEmpty(tvSex.getText().toString().trim())){
            Utils.showToastSafe(tvSex.getHint().toString());
            return;
        }
        if (TextUtils.isEmpty(tvWordTime.getText().toString().trim())){
            Utils.showToastSafe(tvWordTime.getHint().toString());
            return;
        }
        if (TextUtils.isEmpty(tv_word_end_time.getText().toString().trim())){
            Utils.showToastSafe(tv_word_end_time.getHint().toString());
            return;
        }


        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date  mtime1 = sf.parse(tvWordTime.getText().toString());
            Date  mtime2 = sf.parse(tv_word_end_time.getText().toString());

            if(mtime1.getTime() > mtime2.getTime()){
                Utils.showToastSafe("开始日期不能晚于结束日期");
                return;
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (TextUtils.isEmpty(tv_word_time2.getText().toString().trim())){
            Utils.showToastSafe(tv_word_time2.getHint().toString());
            return;
        }

        if (TextUtils.isEmpty(tvWordAddress.getText().toString().trim())){
            Utils.showToastSafe(tvWordAddress.getHint().toString());
            return;
        }

        if (TextUtils.isEmpty(etOrderWorkAddress.getText().toString().trim())){
            Utils.showToastSafe(etOrderWorkAddress.getHint().toString());
            return;
        }

       /* if (TextUtils.isEmpty(etOrderPositionDescribe.getText().toString().trim())){
            Utils.showToastSafe(etOrderPositionDescribe.getHint().toString());
            return;
        }*/
        if (TextUtils.isEmpty(etOrderContacts.getText().toString().trim())){
            Utils.showToastSafe(etOrderContacts.getHint().toString());
            return;
        }

        if (!Utils.isPhoneNumber(etOrderContactsPhone.getText().toString())){
            Utils.showToastSafe("请输入正确的手机号码");
            return;
        }

        if (!cb1.isChecked() && !cb2.isChecked() && !cb3.isChecked()){
            Utils.showToastSafe("请选择项目方式");
            return;
        }
        if (!cb4.isChecked()){
            Utils.showToastSafe("请阅读并同意并勾选个人协议");
            return;
        }

        /*if (flag){
            showPossWord();
            return;
        }*/


        Map<String, Object> params = new HashMap<>();
        if (null != orderDetail){
            params.put("Order_ID", orderDetail.getOrder().getOrder_ID());
            params.put("Order_PositionID",orderDetail.getOrder().getOrder_PositionID());
        }else {
            params.put("Order_ID", "");
            params.put("Order_PositionID",position_id);
        }

        params.put("Order_OrderNum", "");
        //发布人id
        params.put("Order_BusinessID", SPUtil.getString(Constants.USERID));
        //发布人姓名
        params.put("Order_BusinessName", "");
        params.put("Order_EnterpriseID", "");
        //企业名称
        params.put("Order_EnterpriseName", "");
       // params.put("Order_Title",etOrderTitle.getText().toString().trim());

        params.put("Order_PositionName",tvOrderPositionName.getText().toString().trim());
        if (tvOrderPositionType.getText().toString().trim().equals("全职")){
            params.put("Order_PositionType",1 + "");
        }else {
            params.put("Order_PositionType",0 + "");
        }

        params.put("Order_Number",etOrderNumber.getText().toString().trim());
        params.put("Order_Salary",etOrderSalary.getText().toString().trim());
        params.put("Order_SalaryType",order_salaryType + "");
        params.put("Order_Welfare",tvWelfare.getText().toString().trim()); //职位福利
        params.put("Order_Education",tvRecord.getText().toString().trim());
        params.put("Order_WorkYears",tvYearTime.getText().toString().trim());
        params.put("Order_Sex",tvSex.getText().toString().trim());
        params.put("Order_Age",tvYear.getText().toString().trim());
        params.put("Order_EndTime",tv_word_end_time.getText().toString().trim());
        params.put("Order_StartTime",tvWordTime.getText().toString().trim());
        params.put("Order_HourStartTime",tv_word_time2.getText().toString().trim().split("—")[0]);
        params.put("Order_HourEndTime",tv_word_time2.getText().toString().trim().split("—")[1]);
        params.put("Order_WorkTimeNum","");
        params.put("Order_WorkAddress",address);
        params.put("Order_WorkDetailedAddress",etOrderWorkAddress.getText().toString().trim());

        params.put("Order_WorkLat", latitude + "");
        params.put("Order_WorkLng", longitude + "");

        params.put("Order_PositionDescribe",etOrderPositionDescribe.getText().toString().trim());
        params.put("Order_Contacts",etOrderContacts.getText().toString().trim());
        params.put("Order_ContactsPhone",etOrderContactsPhone.getText().toString().trim());
        params.put("Order_Mail",etOrderMail.getText().toString().trim());
        params.put("Order_Type", order_type + ""); //项目方式
        params.put("Order_State",""); //状态
        params.put("Order_CreateTime","");
        params.put("Order_Bond","");
        params.put("Order_ServiceCharge","");
        params.put("Order_ItemServiceCharge","");


        HttpClient.post(PostJobActivity.this, Constants.ADDORDER, params, new CallBack<OrderDetail>() {
            @Override
            public void onSuccess(OrderDetail result) {
                order_bond = result.Order_Bond;
                order_id = result.Order_ID;
                flag = true;
                if (null != orderDetail){
                      // Utils.showToastSafe("修改成功");
                       showPossWord();
                     //  finish();
                   }else {
                      // Utils.showToastSafe("发布成功");
                       showPossWord();
                   }
            }
        });
    }

    private String alreadyInputPassword;
    private boolean isFirstInputPassword = true;
    private boolean isCanClear = true;
    private EditText et_password;
    private void showPossWord() {
        setBackgroundAlpha((float) 0.4);
        View contentView = LayoutInflater.from(this).inflate(R.layout.popwindow_validate_pay_password, null);
        et_password = contentView.findViewById(R.id.et_password);
        final TextView tv_pwd_one = contentView.findViewById(R.id.tv_pwd_one);
        final TextView tv_pwd_two = contentView.findViewById(R.id.tv_pwd_two);
        final TextView tv_pwd_three = contentView.findViewById(R.id.tv_pwd_three);
        final TextView tv_pwd_four = contentView.findViewById(R.id.tv_pwd_four);
        final TextView tv_pwd_five = contentView.findViewById(R.id.tv_pwd_five);
        final TextView tv_pwd_six = contentView.findViewById(R.id.tv_pwd_six);
        final ImageView iv_close = contentView.findViewById(R.id.iv_close);
        final TextView tv_forget_password = contentView.findViewById(R.id.tv_forget_password);
        final TextView tv_money = contentView.findViewById(R.id.tv_money);
        tv_money.setText("￥ " + new DecimalFormat("#.00").format(order_bond));
        tv_pwd_one.setOnClickListener(this);
        tv_pwd_two.setOnClickListener(this);
        tv_pwd_three.setOnClickListener(this);
        tv_pwd_four.setOnClickListener(this);
        tv_pwd_five.setOnClickListener(this);
        tv_pwd_six.setOnClickListener(this);
        iv_close.setOnClickListener(this);
        tv_forget_password.setOnClickListener(this);

        et_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                switch (s.length()) {
                    case 0:
                        if (isCanClear) {
                            tv_pwd_one.setText("");
                        }
                        break;
                    case 1:
                        tv_pwd_one.setText(s.toString().substring(0, 1));
                        tv_pwd_two.setText("");
                        break;
                    case 2:
                        tv_pwd_two.setText(s.toString().substring(1, 2));
                        tv_pwd_three.setText("");
                        break;
                    case 3:
                        tv_pwd_three.setText(s.toString().substring(2, 3));
                        tv_pwd_four.setText("");
                        break;
                    case 4:
                        tv_pwd_four.setText(s.toString().substring(3, 4));
                        tv_pwd_five.setText("");
                        break;
                    case 5:
                        tv_pwd_five.setText(s.toString().substring(4, 5));
                        tv_pwd_six.setText("");
                        break;
                    case 6:
                        if (!isFirstInputPassword) {
                            if (s.toString().equals(alreadyInputPassword)) {
                                //密码通过
                                setPayPwd(alreadyInputPassword);
                            } else {
                                //
                            }
                        }
                        tv_pwd_six.setText(s.toString().substring(5, 6));
                        if (isFirstInputPassword) {
                            alreadyInputPassword = s.toString();
                            if (s.toString().equals(alreadyInputPassword))
                                setPayPwd(alreadyInputPassword);
                            // isFirstInputPassword = false;
                        }

                        //  Utils.showToastSafe("支付密码输入错误");
                        tv_pwd_one.setText("");
                        tv_pwd_two.setText("");
                        tv_pwd_three.setText("");
                        tv_pwd_four.setText("");
                        tv_pwd_five.setText("");
                        tv_pwd_six.setText("");
                        isCanClear = false;
                        et_password.setText("");
                        isCanClear = true;
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        mValidatePayPasswordPopWindow = new PopupWindow(contentView,
                (int) (getDeviceDensity().widthPixels / 1.1), LinearLayout.LayoutParams.WRAP_CONTENT, true);
        mValidatePayPasswordPopWindow.setContentView(contentView);
        mValidatePayPasswordPopWindow.setFocusable(true);

        //设置获得焦点，否则无法点击
        //   mValidatePayPasswordPopWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        //   mValidatePayPasswordPopWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        View rootView = LayoutInflater.from(this).inflate(R.layout.hot_job_activity, null);
        mValidatePayPasswordPopWindow.showAtLocation(rootView, Gravity.CENTER, 0, 0);
        //    openKeybord();
        mValidatePayPasswordPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBackgroundAlpha(1);
            }
        });

    }

    private void setPayPwd(String alreadyInputPassword) {
        Map<String, Object> params = new HashMap<>();
        params.put("UserID", SPUtil.getString(Constants.USERID));
        params.put("Pwd", alreadyInputPassword);
        HttpClient.get(PostJobActivity.this, Constants.VERIFICATIONPWDBY, params, new CallBack<LoginBean>() {
            @Override
            public void onSuccess(LoginBean result) {
                if (type2 == 1){
                    Map<String, Object> params = new HashMap<>();
                    params.put("OrderID", new_Order_id);
                    params.put("OldOrderID", orderDetail.getOrder().getOrder_ID());
                    params.put("UserID", SPUtil.getString(Constants.USERID));
                    HttpClient.get(PostJobActivity.this, Constants.TURNOUTORDERMONEY, params, new CallBack<LoginBean>() {
                        @Override
                        public void onSuccess(LoginBean result) {
                            mValidatePayPasswordPopWindow.dismiss();
                            Utils.showToastSafe("转发成功");
                            MessageEvent messageEvent = new MessageEvent();
                            messageEvent.setMessageKey(EventConstants.PAY);
                            EventBus.getDefault().post(messageEvent);
                            finish();
                            //    getOrderInfo();
                        }
                    });
                }else {
                    Map<String, Object> params = new HashMap<>();
                    params.put("OrderID", order_id);
                    params.put("UserID", SPUtil.getString(Constants.USERID));
                    params.put("PayPwd", alreadyInputPassword);
                    HttpClient.get(PostJobActivity.this, Constants.CALCULATIONMONEY, params, new CallBack<LoginBean>() {
                        @Override
                        public void onSuccess(LoginBean result) {
                            mValidatePayPasswordPopWindow.dismiss();
                            if (type2 == 1){
                                Utils.showToastSafe("转发成功");
                            }else {
                                Utils.showToastSafe("发布成功");
                            }

                            // sbApply.setVisibility(View.INVISIBLE);
                            MessageEvent messageEvent = new MessageEvent();
                            messageEvent.setMessageKey(EventConstants.PAY);
                            EventBus.getDefault().post(messageEvent);
                            finish();
                            //    getOrderInfo();
                        }
                    });

                }

            }
        });
    }

    private void showWordTime(int type) {
        hideInput2();
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        startDate.set(2013, 1, 1);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2030, 1, 1);

        TimePickerView pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                if (type == 1) {
                    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        Date  mtime1 = sf.parse(Utils.getDayTime());
                        Date  mtime2 = sf.parse(Utils.getTime2(date));
                        if (mtime2.getTime() > mtime1.getTime()){
                            tvWordTime.setText(Utils.getTime2(date));
                        }else {
                            Utils.showToastSafe("开始日期须大于今天日期");
                            return;
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                } else {
                    tv_word_end_time.setText(Utils.getTime2(date));
                }
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})//默
                .setTitleText(typeName)
                .setSubmitText("确定")//确定按钮文字
                .setCancelText("取消")//取消按钮文字
                .setSubCalSize(10)//确定和取消文字大小
                .setSubmitColor(0xffFF6767)//确定按钮文字颜色
                .setCancelColor(0xff999999)//取消按钮文字颜色
                .setTitleBgColor(0xffF4F4F4)//标题背景颜色 Night mode
                .setTitleSize(10)
                .setContentTextSize(12)//滚轮文字大小
                .setTextColorCenter(0xff333333)
                .isCyclic(true)//是否循环滚动
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .setTextColorOut(0x999999)
                .setDividerColor(0xffEEEEEE)
                .setLabel("年", "月", "日", "时", "分", "秒")
                .setOutSideCancelable(true)//点击外部dismiss default true
                .isDialog(false)//是否显示为对话框样式
                .setLineSpacingMultiplier((float) 2.5) //设置item的高度
                .build();
        //注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        pvTime.setDate(Calendar.getInstance());
        pvTime.show();
    }

    private void showSex(int type) {
        hideInput2();
        if (type == 1) {
            gradeData.clear();
            gradeData.add("不限");
            gradeData.add("男");
            gradeData.add("女");
        } else if (type == 2) {
            gradeData.clear();
            gradeData.add("高中以下");
            gradeData.add("高中");
            gradeData.add("中专/技校");
            gradeData.add("大专");
            gradeData.add("本科");
            gradeData.add("硕士");
            gradeData.add("博士");
        } else if (type == 3) {
            gradeData.clear();
            gradeData.add("不限");
            gradeData.add("1年以下");
            gradeData.add("1-2年");
            gradeData.add("3-5年");
            gradeData.add("6-7年");
            gradeData.add("8-10年");
            gradeData.add("10年以上");
        } else if (type == 4) {
            gradeData.clear();
            gradeData.add("不限");
            gradeData.add("18-30岁");
            gradeData.add("30-40岁");
            gradeData.add("50岁以下");
        }else {
            gradeData.clear();
            gradeData.add("全职");
            gradeData.add("兼职");
        }
        pvOptions = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            if (type == 1) {
                tvSex.setText(gradeData.get(options1));
            } else if (type == 2) {
                //学历
                typeName = "学历";
                tvRecord.setText(gradeData.get(options1));
            } else if (type == 3) {
                typeName = "工作年限";
                tvYearTime.setText(gradeData.get(options1));
            } else if (type == 4) {
                typeName = "年龄要求";
                tvYear.setText(gradeData.get(options1));
            }else {
                tvOrderPositionType.setText(gradeData.get(options1));
            }
        })
                .setTitleText(typeName)
                .setSubmitText("确定")//确定按钮文字
                .setCancelText("取消")//取消按钮文字
                .setSubCalSize(10)//确定和取消文字大小
                .setSubmitColor(0xffFF6767)//确定按钮文字颜色
                .setCancelColor(0xff999999)//取消按钮文字颜色
                .setTitleBgColor(0xffF4F4F4)//标题背景颜色 Night mode
                .setTitleSize(10)
                .setContentTextSize(12)//滚轮文字大小
                .setTextColorCenter(0xff333333)
                .setTextColorOut(0x999999)
                .setDividerColor(0xffEEEEEE)
                .setCyclic(false, false, false)//循环与否
                .setSelectOptions(0, 0, 0)  //设置默认选中项
                .setOutSideCancelable(true)//点击外部dismiss default true
                .isDialog(false)//是否显示为对话框样式
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .setLineSpacingMultiplier((float) 2.5) //设置item的高度
                .build();
        pvOptions.setPicker(gradeData);
        pvOptions.show();
    }


    private void showAddress() {
        hideInput2();
        //申明对象
        CityPickerView mPicker = new CityPickerView();
        //预先加载仿iOS滚轮实现的全部数据（oncreate()中）
        mPicker.init(this);

        //配置
        CityConfig cityConfig = new CityConfig.Builder()
                .title("选择城市")//标题
                .titleTextSize(10)//标题文字大小
                .titleTextColor("#585858")//标题文字颜  色
                .titleBackgroundColor("#ffdddddd")//标题栏背景色
                .confirTextColor("#ffe1163c")//确认按钮文字颜色
                .confirmText("确定")//确认按钮文字
                .confirmTextSize(10)//确认按钮文字大小
                .cancelTextColor("#585858")//取消按钮文字颜色
                .cancelText("取消")//取消按钮文字
                .cancelTextSize(10)//取消按钮文字大小
                .setCityWheelType(CityConfig.WheelType.PRO_CITY_DIS)//显示类，只显示省份一级，显示省市两级还是显示省市区三级
                .showBackground(true)//是否显示半透明背景
                .visibleItemsCount(7)//显示item的数量
                .province("湖北省")//默认显示的省份
                .city("武汉市")//默认显示省份下面的城市
                .district("洪山区")//默认显示省市下面的区县数据
                .provinceCyclic(true)//省份滚轮是否可以循环滚动
                .cityCyclic(true)//城市滚轮是否可以循环滚动
                .districtCyclic(true)//区县滚轮是否循环滚动
                .setCustomItemLayout(R.layout.item_city)//自定义item的布局
                .setCustomItemTextViewId(R.id.item_city_name_tv)//自定义item布局里面的textViewid
                .drawShadows(false)//滚轮不显示模糊效果
                .setLineHeigh(1)//中间横线的高度
                .setLineColor("#fff9c21a")
                .setShowGAT(true)//是否显示港澳台数据，默认不显示
                .build();
        //添加配置
        mPicker.setConfig(cityConfig);
        //显示
        mPicker.showCityPicker();
        //监听选择点击事件及返回结果
        mPicker.setOnCityItemClickListener(new OnCityItemClickListener() {
            @Override
            public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                super.onSelected(province, city, district);
                //为TextView赋值
                tvWordAddress.setText(province + "-" + city + "-" + district);
                address = province + "," + city + "," + district;
            }

            @Override
            public void onCancel() {
                super.onCancel();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 30 && resultCode == 20) {
            position_id = data.getStringExtra("position_id");
            String position_name = data.getStringExtra("position_name");
            tvOrderPositionName.setText(position_name);
        }else if (requestCode == 5 && resultCode == -1){
            String address = data.getStringExtra("address");
            latitude = data.getDoubleExtra("latitude",0);
            longitude = data.getDoubleExtra("longitude",0);
           // intent.putExtra("latitude", latLngEntity.getLatitude());
           // intent.putExtra("longitude", latLngEntity.getLongitude());

            etOrderWorkAddress.setText(address);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_pwd_one:
            case R.id.tv_pwd_two:
            case R.id.tv_pwd_three:
            case R.id.tv_pwd_four:
            case R.id.tv_pwd_five:
            case R.id.tv_pwd_six:
                CommonUtil.showKeyboard(this, et_password, true);
                break;
            case R.id.iv_close:
                mValidatePayPasswordPopWindow.dismiss();
                break;
            case R.id.tv_forget_password:
                Utils.startActivity(ResetPayActivity.class);
                mValidatePayPasswordPopWindow.dismiss();
                break;
            default:
                break;
        }
    }
}
